﻿using Microsoft.AspNetCore.Authorization;
using System.Collections.Generic;
using System.Security.Claims;

namespace D.UtilCore.JwtUtil
{

    public class PermissionRequirement : IAuthorizationRequirement
    {
        public string Url { get; set; }
        public List<string> Roles { get; set; }
    }

    public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
    {
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            //模拟从数据库或者缓存中取出的访问url的权限数据
            var roles = new List<PermissionRequirement>();
            roles.Add(new PermissionRequirement() { Url = "weatherforecast", Roles = new List<string>() { "system" } });

            //JWT的token中的声明等信息都会自动解析在context中
            var resource = ((Microsoft.AspNetCore.Routing.RouteEndpoint)context.Resource).RoutePattern;
            foreach (var t in context.User.Identities)
            {
                foreach (var claim in t.Claims)
                {
                    //通过Type可以判断声明的类型，这里处理role的声明获取角色信息
                    if (claim.Type == ClaimTypes.Role)
                    {
                        if (roles.Exists(x => x.Roles.Exists(role => role == claim.Value) && x.Url == resource.RawText.ToLower()))
                        {
                            context.Succeed(requirement);
                            return;
                        }
                    }
                }
            }
            context.Fail();
            return;
        }
    }
}



